package middlewares

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"strings"
)

func DefaultValidator(c *gin.Context, params interface{}) error {
	if err := c.ShouldBind(params); err != nil {
		return err
	}
	// ---------------------------------------------------------------中文翻译器
	uni := ut.New(zh.New())
	trans, _ := uni.GetTranslator("zh")

	//=================================================================实例化验证器
	validate := validator.New()
	//==================================================================注册备用字段名字
	validate.RegisterTagNameFunc(func(field reflect.StructField) string {
		return field.Tag.Get("name")
	})
	// ===============================================================注册翻译器到校验器
	err := zh_translations.RegisterDefaultTranslations(validate, trans)
	if err != nil {
		return err
	}
	//===================================================================校验参数
	errs := validate.Struct(params)
	if errs != nil {
		var sliceErrs []string
		for _, err := range errs.(validator.ValidationErrors) {
			sliceErrs = append(sliceErrs, err.Translate(trans))
		}
		return errors.New(strings.Join(sliceErrs, ","))
	}
	return nil

}
